<template>
  <div class="operation-log">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.reportName"
            placeholder="搜索报告名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.reportOwner"
            placeholder="搜索报告所属人"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.reportType"
            placeholder="报告类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in dictData.healthTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.operator"
            placeholder="搜索上传报告人"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="reportName"
          label="报告名称"
          show-overflow-tooltip
        />
        <el-table-column prop="reportUserName" label="报告所属人" />
        <el-table-column prop="reportType" label="报告类型">
          <template #default="scope">
            {{ getReportTypeName(scope.row.reportType) }}
          </template>
        </el-table-column>
        <el-table-column prop="operateName" label="操作者" />
        <el-table-column
          prop="operateTime"
          label="操作时间"
          width="200"
          sortable
        />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              v-show="scope.row.showSupplementButton"
              type="primary"
              link
              @click="openEditDialog(scope.row)"
            >
              补充报告所属人
            </el-button>
            <el-button type="primary" link @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 编辑报告所属人弹窗 -->
    <EditReportUser
      ref="editUserDialogRef"
      :report-id="currentReportId"
      :current-name="currentUserName"
      @update="handleUpdateUser"
      @close="handleEditDialogClose"
    />

    <!-- 操作日志详情抽屉 -->
    <LogDetail
      title="操作日志详情"
      v-model="detailDrawerVisible"
      :operate-log-id="currentOperateLogId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addReportApi,
  type OperateLogParams,
  type OperateLogItem
} from "@/api/addReport";
import { ReportSearchConditionVO } from "@/api/types";
import { reportApi } from "@/api/report-api";
import EditReportUser from "@/components/EditReportUser/index.vue";
import { ReportOperateLogDetailVO } from "@/api/addReport";
import LogDetail from "./logDetail.vue";
const dictData = ref<ReportSearchConditionVO>({});

const operateDetail = ref<ReportOperateLogDetailVO>();
const detailLoading = ref(false);

// 抽屉状态管理
const detailDrawerVisible = ref(false);
const currentOperateLogId = ref<number>(0);

// 编辑用户弹窗相关
const editUserDialogRef = ref();
const currentReportId = ref<number>();
const currentUserName = ref("");
// 打开编辑弹窗
const openEditDialog = (row: any) => {
  console.log("row", row);
  currentReportId.value = row.reportId;
  currentUserName.value = row.reportUserName || "";
  editUserDialogRef.value?.open(row.reportUserName);
};
// 关闭编辑弹窗
const handleEditDialogClose = () => {
  currentReportId.value = undefined;
  currentUserName.value = "";
};

// 查看详情 - 打开抽屉
const handleViewDetail = (row: OperateLogItem) => {
  console.log("查看详情 - 操作日志ID:", row.operateLogId);

  if (!row.operateLogId) {
    console.warn("操作日志ID为空，无法查看详情");
    ElMessage.warning("操作日志ID为空，无法查看详情");
    return;
  }

  // 设置当前操作日志ID并打开抽屉
  currentOperateLogId.value = row.operateLogId;
  detailDrawerVisible.value = true;

  console.log("打开操作日志详情抽屉，ID:", currentOperateLogId.value);
};

// 更新用户信息
const handleUpdateUser = async (data: { reportId?: number; name: string }) => {
  try {
    // TODO: 调用更新用户信息的 API
    // const res = await addReportApi.updateReportUser({
    //   reportId: data.reportId,
    //   userName: data.name
    // });
    ElMessage.success("更新成功");
    // 重新加载数据
    handleSearch();
  } catch (error) {
    console.error("更新用户信息失败:", error);
    ElMessage.error("更新用户信息失败");
  }
};

const getReportTypeName = (reportTypeId: number | string) => {
  const typeItem = dictData.value.healthTypeList?.find(
    item => item.id === reportTypeId
  );
  return typeItem?.name || reportTypeId;
};

// 搜索表单
const searchForm = reactive({
  reportName: "",
  reportOwner: "",
  reportType: "",
  dateRange: [],
  operator: ""
});

// 表格数据
const tableData = ref<OperateLogItem[]>([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 加载状态
const loading = ref(false);

// 搜索
const handleSearch = () => {
  console.log("搜索参数:", searchForm);
  pagination.currentPage = 1; // 重置到第一页
  loadData();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    reportName: "",
    reportOwner: "",
    reportType: "",
    dateRange: [],
    operator: ""
  });
  pagination.currentPage = 1; // 重置到第一页
  loadData();
};
// 补充报告所属人
const handleSupplementOwner = (row: OperateLogItem) => {
  console.log("补充报告所属人:", row);
  ElMessage.info("补充报告所属人功能待实现");
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  loadData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadData();
};
// 构建查询参数
const buildQueryParams = (): OperateLogParams => {
  const params: OperateLogParams = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  };

  // 添加可选的搜索参数
  if (searchForm.reportName.trim()) {
    params.reportName = searchForm.reportName.trim();
  }

  if (searchForm.reportOwner.trim()) {
    params.reportUserName = searchForm.reportOwner.trim();
  }

  if (searchForm.reportType) {
    params.healthTypeId = Number(searchForm.reportType);
  }

  if (searchForm.operator.trim()) {
    params.uploadUserName = searchForm.operator.trim();
  }

  // 处理日期范围（如果需要的话，可以添加到API参数中）
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    // 根据API需要添加日期参数
    params.startDate = searchForm.dateRange[0];
    params.endDate = searchForm.dateRange[1];
  }

  return params;
};
// 加载数据
const loadData = async () => {
  try {
    loading.value = true;

    const params = buildQueryParams();
    console.log("请求参数:", params);

    const response = await addReportApi.getOperateLog(params);

    if (response.code === 0 && response.data) {
      tableData.value = response.data.list || [];
      pagination.total = response.data.total || 0;

      console.log("加载数据完成", {
        total: pagination.total,
        list: tableData.value.length
      });
    } else {
      ElMessage.error(response.message || "获取数据失败");
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};
// 获取字典数据
async function queryDictionaryData() {
  try {
    const response = await reportApi.queryReportDict();
    if (response?.data) {
      dictData.value = response.data;
    }
  } catch (err) {
    console.error("获取字典数据失败:", err);
    ElMessage.error("获取字典数据失败");
  }
}

// 页面初始化
onMounted(() => {
  queryDictionaryData();
  loadData();
});
</script>

<style scoped lang="scss">
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
